const CryptoJS = require('./crypto-js/crypto-js')
var iv = "Ch7juDLTLwZgQNvq"
// 加密参数
function encrypt(key, word) {
  try {
    // Encrypt
    var str = JSON.stringify(word);
    var pkey = CryptoJS.enc.Utf8.parse(key);
    var encrypted = CryptoJS.AES.encrypt(str, pkey, {
      iv: CryptoJS.enc.Utf8.parse(iv),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    encrypted = encrypted.toString()
    return encrypted;
  } catch (e) { 
    console.error(e);
  }
  return null;
}

// 解密参数
function decrypt(key, data) {
  try {
    var bytes  = CryptoJS.AES.decrypt(data, CryptoJS.enc.Utf8.parse(key),{
      iv: CryptoJS.enc.Utf8.parse(iv),
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
    var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
    return decryptedData
  } catch (e) {
    console.log(e, "decrypt 的 err值为");
    return data;
  }
}
/**
 * 判断是否是Base64格式的字符串
 */
function isBase64(str) {
  let reg = /^(([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=))|(([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==))$/;
  return reg.test(str);
}

module.exports = {
  encrypt,
  decrypt
}
